package redis.lua;

import org.junit.Before;
import org.junit.Test;
import redis.RedisUtils;
import redis.clients.jedis.Jedis;

/**
 * @author : yang.xp
 * @date : 2022/9/2 15:30
 * @description : redis lua 的测试
 */
public class RedisLuaTest {

    @Before
    public void initRedis() {

    }

    @Test
    public void test1() {
        RedisUtils.init("127.0.0.1", 6379, "", "");
        Jedis jedis = RedisUtils.getJedis();
        System.out.println(jedis.scriptExists("5332031c6b470dc5a0dd9b4bf2030dea6d65de91"));
        System.out.println(jedis.eval("return {KEYS[1],ARGV[1],ARGV[2]}", 1, "keys", "arg1", "arg2"));
        // 载入一个脚本，生成sha1
        String sha1 = jedis.scriptLoad("return 'hello world'");
        System.out.println(sha1);
        System.out.println(jedis.evalsha(sha1));
        // 清除redis所有脚本
//        jedis.scriptFlush();
        System.out.println(jedis.scriptExists(sha1));
        System.out.println(jedis.evalsha(sha1));
        //
        String scoreKey = "score_1";
        jedis.set(scoreKey, String.valueOf(1001));
        System.out.println(scoreAdd1(scoreKey));

        Object eval = jedis.eval("redis.call('incr', 'score_1')");
        System.out.println(eval);
        System.out.println(jedis.get(scoreKey));

    }

    public String scoreAdd1(String key) {
        Jedis jedis = RedisUtils.getJedis();
        jedis.evalsha(jedis.scriptLoad("redis.call('incr', KEYS[1])"), 1, key);
        return jedis.get(key);
    }
}
